package com.h2cloud.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.h2cloud.config.OSSProperties;
import com.h2cloud.entity.BaseResp;
import com.h2cloud.entity.Result;
import com.h2cloud.entity.UserInfo;
import com.h2cloud.service.ResultService;
import com.h2cloud.service.UserInfoService;
import com.h2cloud.utils.CrowdUtil;
import com.h2cloud.utils.JWTUtil;
import com.h2cloud.utils.TencentCOS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;


@RequestMapping("ossfile")
@RestController
public class tencentFileUpload {

    @Autowired
    private OSSProperties ossProperties;

    @Resource
    private ResultService Service;

    @Autowired
    private UserInfoService userInfoService;


    //homePage.html 图片上传
    @PostMapping("/uploadHomePagePic")
    public Object fileupload(MultipartFile file, HttpServletRequest request) throws IOException {
        System.out.println("uploadHomePagePic");

        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("fileupload  /upload-vue ");
        System.out.println(file.getOriginalFilename());
        //保存结果
        Map<String, Object> result = new HashMap<>();

        String url = TencentCOS.uploadfile2(file.getOriginalFilename(), file.getInputStream(), "uploadHomePagePic");
        System.out.println("tencentFileUpload:  " + url);

        BaseResp baseResp = new BaseResp();
        try {
            // 筛查图片
            result.put("url", url);

            //筛查算法.....
//            Connection.Response res = Jsoup
////                    .connect("http://localhost:8888?path="+realPath + fileName)
//                    .connect("http://localhost:8082/medicalhelper/getstatus")
//                    .timeout(10000)
//                    .ignoreContentType(true)
//                    .execute();
//            JSONObject resJson = JSON.parseObject(res.body());

            JSONObject resJson = JSON.parseObject(getstatus());
            System.out.println(resJson);

            result.put("negative", resJson.getString("negative")); // 阳性概率
            result.put("positive", resJson.getString("positive")); // 阴性概率
            Timestamp checkTime = new Timestamp(System.currentTimeMillis()); // 筛查时间
            result.put("time", checkTime);

            String token = request.getHeader("Authorization");
            System.out.println(token);
            String userid = JWTUtil.getToken(token).getClaim("id").asString();

            Result data = new Result();
            data.setUserid(Integer.parseInt(userid));
            data.setTime(checkTime);
            data.setPic(url);
            data.setNegative(resJson.getString("negative"));
            data.setPositive(resJson.getString("positive"));
            data.setFinalResult(-1);
            data.setStatus(0);
            System.out.println("fileUpdate:" + data.toString());
            Result dbdata = Service.insert(data);

            result.put("id", dbdata.getId());
            System.out.println(result);


            baseResp.setCode(BaseResp.HANDLE_SUCCESS);
            baseResp.setMsg("图片处理成功");
            baseResp.setData(result);

        } catch (Exception e) {
            e.printStackTrace();
            baseResp.setCode(BaseResp.HANDLE_ERROR);
            baseResp.setMsg("图片处理失败");
            baseResp.setData(result);

        }
        return baseResp;
    }

    //md 编辑器图片上传
    @ResponseBody
    @PostMapping("/uploadBlogPic")
    public JSONObject upLoad(@RequestParam(value = "file", required = false) MultipartFile file) {

        JSONObject object = new JSONObject();
        try {

            String url = TencentCOS.uploadfile2(file.getOriginalFilename(), file.getInputStream(), "uploadBlogPic");

            System.out.println("图片访问url：" + url);
            object.put("success", 1);
            object.put("message", "上传成功");
            object.put("url", url);

        } catch (Exception e) {

            object.put("success", 0);
            object.put("message", "上传失败");
        }

        return object;
    }

    //mycenter.html 用户头像上传
    @PostMapping("/uploadUserPic")
    public Object userPicUpload(MultipartFile file, HttpServletRequest request) {
        System.out.println("fileupload  /upload-userPic ");
        //保存结果
        Map<String, Object> result = new HashMap<>();

        BaseResp baseResp = new BaseResp();
        try {

            String url = TencentCOS.uploadfile2(file.getOriginalFilename(), file.getInputStream(), "uploadUserPic");
            System.out.println("uploadUserPic:  " + url);

            result.put("url", url);

            baseResp.setCode(BaseResp.HANDLE_SUCCESS);
            baseResp.setMsg("图片处理成功");
            baseResp.setData(result);


            String token = request.getHeader("Authorization");
            System.out.println(token);
            String userid = JWTUtil.getToken(token).getClaim("id").asString();
            UserInfo userInfo = new UserInfo();
            userInfo.setId(Integer.parseInt(userid));
            userInfo.setPic(url);

            userInfoService.update(userInfo);

        } catch (IOException e) {

            baseResp.setCode(BaseResp.HANDLE_ERROR);
            baseResp.setMsg("图片处理失败");
            baseResp.setData(result);

        }
        return baseResp;
    }

    //获取结果
    @GetMapping("/getstatus")
    public String getstatus() {
        Map<String, Object> result = new HashMap<>();
        result.put("status", 1);//请求状态

//        DecimalFormat df = new DecimalFormat("0.0000");
//        double num1 = Double.parseDouble(df.format(new Random().nextDouble())) * 100;

        BigDecimal a = new BigDecimal(new Random().nextDouble() * 100).setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal b = new BigDecimal(100 - a.doubleValue()).setScale(2, BigDecimal.ROUND_HALF_UP);

        result.put("negative", a); // 阴性概率
        result.put("positive", b); // 阴性概率

        return JSON.toJSONString(result);
    }
}
